package com.top.web.hooker.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GroupList<TKey, TValue>
{
    private Map<TKey, List<TValue>> _groupMap;
    private List<TKey> _keyList;
    private int _size = 0;

    public int getTotal()
    {
        return  _size;
    }

    public GroupList()
    {
        _groupMap = new HashMap<TKey, List<TValue>>();
        _keyList = new ArrayList<TKey>();
    }

    public void put(TKey key, TValue value)
    {

        List<TValue> list = _groupMap.get(key);

        if (list == null)
        {
            list = new ArrayList<TValue>();
            _keyList.add(key);
            _groupMap.put(key, list);
        }

        list.add(value);
        _size++;
    }

    public void remove(TKey key)
    {
        if (_groupMap.containsKey(key))
        {
            _groupMap.remove(key);
            _keyList.remove(key);
            _size--;
        }
    }

    public void remove(TKey key, TValue value)
    {
        List<TValue> list = _groupMap.get(key);
        if (list != null)
        {
            list.remove(value);
            if (list.size() == 0)
            {
                _groupMap.remove(key);
                _keyList.remove(key);
                _size--;
            }
        }
    }

    public Set<TKey> keySet()
    {
        return _groupMap.keySet();
    }

    public List<TValue> get(TKey key)
    {
        return _groupMap.get(key);
    }

    public TValue get(TKey key, int i)
    {
        List<TValue> list = _groupMap.get(key);

        if (list != null)
            return list.get(i);

        return null;
    }

    public TKey getKey(int i)
    {
        return _keyList.get(i);
    }

    public int size()
    {
        return _groupMap.size();
    }

    public List<TValue> toList()
    {
        List<TValue> list = new ArrayList<TValue>();

        for (TKey key : _groupMap.keySet())
        {
            list.addAll(_groupMap.get(key));
        }

        return list;
    }
}
